package com.gaohe.scp.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

import com.gaohe.common.utils.DateUtils;
import com.gaohe.common.utils.SecurityUtils;
import com.gaohe.scp.domain.CsCar;
import com.gaohe.scp.domain.CsCarQuote;
import com.gaohe.scp.domain.vo.CarAutoDto;
import com.gaohe.scp.domain.vo.CsRecordVo;
import com.gaohe.scp.mapper.CsCarMapper;
import com.gaohe.scp.mapper.CsCarQuoteMapper;
import com.gaohe.scp.domain.CsCar;
import com.gaohe.scp.mapper.CsCarMapper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.gaohe.scp.mapper.CsAuctionMapper;
import com.gaohe.scp.domain.CsAuction;
import com.gaohe.scp.service.ICsAuctionService;

/**
 * 竞拍记录Service业务层处理
 *
 * @author liuxiangyu
 * @date 2025-03-25
 */
@Service
public class CsAuctionServiceImpl implements ICsAuctionService
{
    @Autowired
    private CsAuctionMapper csAuctionMapper;
    @Autowired
    private CsCarQuoteMapper csCarQuoteMapper;
    @Autowired
    private CsCarMapper csCarMapper;

    /**
     * 查询竞拍记录
     *
     * @param auctionId 竞拍记录主键
     * @return 竞拍记录
     */
    @Override
    public CsAuction selectCsAuctionByAuctionId(Long auctionId)
    {
        return csAuctionMapper.selectCsAuctionByAuctionId(auctionId);
    }
    //    根据carid查询竞拍记录
    @Override
    public List<CsAuction> selectCsAuctionByCarId(Long carId)
    {
        return csAuctionMapper.selectCsAuctionByCarId(carId);
    }

    /**
     * 参拍记录擦查询
     *
     * @param userId 用户
     * @return
     */
    @Override
    public List<CsRecordVo> selectCsAuctionByUserId(Long userId) {

        return csAuctionMapper.SelectCsAuctioByUserId(userId);
    }

    /**
     * 查询竞拍记录列表
     *
     * @param csAuction 竞拍记录
     * @return 竞拍记录
     */
    @Override
    public List<CsAuction> selectCsAuctionList(CsAuction csAuction)
    {
        return csAuctionMapper.selectCsAuctionList(csAuction);
    }

    /**
     * 查询竞拍记录列表
     * 张文豪
     * @param csAuction 竞拍记录
     * @return 竞拍记录
     */
    @Override
    public List<CsAuction> selectCsAuctionListGld(CsAuction csAuction)
    {
        List<CsAuction> auctionList = csAuctionMapper.selectCsAuctionList(csAuction);
        System.err.println(auctionList);
        if (auctionList == null||auctionList.size()==0  ){
            return null;
        }
        auctionList.sort(Comparator.comparing(CsAuction::getPrice).reversed());
        for (CsAuction auction : auctionList) {
            auction.setRemark("落后");
        }
        auctionList.get(0).setRemark("领先");
        return auctionList;
    }

    /**
     * 新增竞拍记录
     *
     * @param csAuction 竞拍记录
     * @return 结果
     */
    @Override
    public int insertCsAuction(CsAuction csAuction)
    {
        csAuction.setCreateTime(DateUtils.getNowDate());
        return csAuctionMapper.insertCsAuction(csAuction);
    }

    /**
     * 修改竞拍记录
     *
     * @param csAuction 竞拍记录
     * @return 结果
     */
    @Override
    public int updateCsAuction(CsAuction csAuction)
    {
        csAuction.setUpdateTime(DateUtils.getNowDate());
        return csAuctionMapper.updateCsAuction(csAuction);
    }

    /**
     * 批量删除竞拍记录
     *
     * @param auctionIds 需要删除的竞拍记录主键
     * @return 结果
     */
    @Override
    public int deleteCsAuctionByAuctionIds(Long[] auctionIds)
    {
        return csAuctionMapper.deleteCsAuctionByAuctionIds(auctionIds);
    }

    /**
     * 删除竞拍记录信息
     *
     * @param auctionId 竞拍记录主键
     * @return 结果
     */
    @Override
    public int deleteCsAuctionByAuctionId(Long auctionId)
    {
        return csAuctionMapper.deleteCsAuctionByAuctionId(auctionId);
    }

    @Override
    public CsCar selectCarNameByCarId(Long carId) {

        return csCarMapper.selectCsCarByCarId(carId);
    }

    //手动出价逻辑
    @Override
    public int insertCsAuctionOrUpdate(CsAuction csAuction) {
        BigDecimal price = csAuction.getPrice();
        //健壮性
        if (csAuction.getUserId() == null || csAuction.getCarId() == null){
            return 0;
        }
        CsCarQuote csCarQuote = csCarQuoteMapper.selectCsCarQuoteByCarId(csAuction.getCarId());
        CsCar csCar = csCarMapper.selectCsCarByCarId(csAuction.getCarId());
        //判断状态 只有状态为进行中的才可以出价
        if (!Objects.equals(csCar.getStatus(), "进行中")){
            return 0;
        }
        //查询一下car表的最低加价 如果 price >= 当前最高价格 + 最低加价 并且price>= 起始价格可执行下一步    + 最低加价
        BigDecimal nowPrice = csCarQuote.getPrice(); //当前最高价格
        BigDecimal addPrice = csCar.getAddPrice(); //最低加价
        BigDecimal startPrice = csCar.getStartPrice(); //初始价格
        if ((price.compareTo(nowPrice.add(addPrice)) < 0) || (price.compareTo(startPrice) < 0)){
            return 0;
        }

        addprice(csAuction, price, csCarQuote, csCar);

        return 1;
    }

    //自动出价
    @Override
    public int insertCsAuctionOrUpdateAuto(CarAutoDto carAutoDto) {
        BigDecimal price = carAutoDto.getPrice();

        //健壮性
        BigDecimal maxPrice = carAutoDto.getMaxPrice();
        if (carAutoDto.getUserId() == null || carAutoDto.getCarId() == null || maxPrice == null){
            return 0;
        }
        //判断当前最高出价者是不是我 如果不是我或该车没有出价记录，那么进行出价，如果我是最高出价者，继续执行定时器
        List<CsAuction> csAuctions = csAuctionMapper.selectCsAuctionByCarId(carAutoDto.getCarId());
        Long userId = SecurityUtils.getUserId();
        if (csAuctions.size() != 0 && Objects.equals(csAuctions.get(0).getUserId(), userId)){
            return 2;
        }

        CsCarQuote csCarQuote = csCarQuoteMapper.selectCsCarQuoteByCarId(carAutoDto.getCarId());
        CsCar csCar = csCarMapper.selectCsCarByCarId(carAutoDto.getCarId());
        //判断状态 只有状态为进行中的才可以出价
        if (!Objects.equals(csCar.getStatus(), "进行中")){
            return 0;
        }
        //查询一下car表的最低加价 如果 price >= 当前最高价格 + 最低加价 并且price>= 起始价格可执行下一步   + 最低加价 .add(addPrice)
        BigDecimal nowPrice = csCarQuote.getPrice(); //当前最高价格
        BigDecimal addPrice = csCar.getAddPrice(); //最低加价
        BigDecimal startPrice = csCar.getStartPrice(); //初始价格

        //如果price > 指定最高价格，停止定时器
        if (price.compareTo(maxPrice) > 0){
            return 0;
        }

        if ((price.compareTo(nowPrice.add(addPrice)) < 0) || (price.compareTo(startPrice) < 0)){
            return 0;
        }


        addprice(carAutoDto, price, csCarQuote, csCar);

        return 1;
    }

    private void addprice(CsAuction csAuction, BigDecimal price, CsCarQuote csCarQuote, CsCar csCar) {
        //通过carId和userId查询数据库是否有该车辆的csAuction
        List<CsAuction> csAuctions = csAuctionMapper.selectCsAuctionByCarIdAndUserId(csAuction);
        if (csAuctions.size() == 0){
            //如果没有 新增记录
            csAuctionMapper.insertCsAuction(csAuction);
        }else {
            //如果有，auction修改记录 分别获取价格
            CsAuction csAuction1 = csAuctions.get(0);
            csAuction1.setPrice(price);
            csAuctionMapper.updateCsAuction(csAuction1);

        }
        //再修改quote 通过carId进行查询
        csCarQuote.setPrice(price);
        csCarQuoteMapper.updateCsCarQuote(csCarQuote);
        //修改后 时间判断 如果在5分钟 那么结束时间延长1分钟
        Date endTime = csCar.getEndTime();
        Date nowDate = DateUtils.getNowDate();
        //剩余结束时间5min前
        Date beforeDate = new Date();
        beforeDate.setTime(endTime.getTime() - 5*60*1000);
        if (beforeDate.before(nowDate)){
            //endTime延长5分钟
            endTime.setTime(endTime.getTime() + 5*60*1000);
            csCar.setEndTime(endTime);
            csCarMapper.updateCsCar(csCar);
        }
    }

    //查询
    @Override
    public BigDecimal getMyAuctionByCarId(Long carId) {
        Long userId = SecurityUtils.getUserId();
        CsAuction csAuction = new CsAuction();
        csAuction.setUserId(userId);
        csAuction.setCarId(carId);
        //通过carId和userId查询我的最高出价
        List<CsAuction> csAuctions = csAuctionMapper.selectCsAuctionByCarIdAndUserId(csAuction);
        if (csAuctions.size() == 0) {
            return new BigDecimal(0);
        }
        return csAuctions.get(0).getPrice();
    }
}
